import React, { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { Form, Input, Button, Card, message } from 'antd';
import { UserOutlined, LockOutlined, MailOutlined } from '@ant-design/icons';
import { authAPI } from '../services/api';
import './Register.css';

const Register = () => {
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const [form] = Form.useForm();

  const onFinish = async (values) => {
    console.log('=== 开始注册流程 ===');
    console.log('1. 表单提交值:', {
      username: values.username,
      email: values.email,
      passwordLength: values.password?.length
    });

    setLoading(true);
    try {
      console.log('2. 开始调用注册API...');
      const response = await authAPI.register({
        username: values.username,
        email: values.email,
        password: values.password,
        role: "陪陪", // 默认角色
        permission: "user" // 默认权限
      });
      
      console.log('3. 注册API响应:', {
        status: response.status,
        data: response.data
      });

      console.log('4. 注册成功，准备跳转...');
      message.success('注册成功，3秒后跳转到登录页面');
      
      // 使用setTimeout确保跳转只发生在注册成功时
      setTimeout(() => {
        console.log('5. 执行跳转到登录页面');
        navigate('/login');
      }, 3000);
    } catch (error) {
      console.log('=== 注册失败 ===');
      console.error('错误详情:', {
        message: error.message,
        response: {
          status: error.response?.status,
          data: error.response?.data
        }
      });
      
      const errorMessage = error.response?.data?.message || '未知错误';
      console.log('显示错误消息:', errorMessage);
      message.error('注册失败：' + errorMessage);
      
      console.log('清空密码字段');
      form.setFieldsValue({
        password: '',
        confirmPassword: ''
      });
    } finally {
      console.log('6. 注册流程结束，重置loading状态');
      setLoading(false);
    }
  };

  return (
    <div className="register-container">
      <Card className="register-card" title="用户注册">
        <Form
          form={form}
          name="register"
          onFinish={onFinish}
          layout="vertical"
        >
          <Form.Item
            name="username"
            rules={[
              { required: true, message: '请输入用户名' },
              { min: 3, message: '用户名至少3个字符' }
            ]}
          >
            <Input prefix={<UserOutlined />} placeholder="用户名" />
          </Form.Item>

          <Form.Item
            name="email"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' }
            ]}
          >
            <Input prefix={<MailOutlined />} placeholder="邮箱" />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[
              { required: true, message: '请输入密码' },
              { min: 6, message: '密码至少6个字符' }
            ]}
          >
            <Input.Password prefix={<LockOutlined />} placeholder="密码" />
          </Form.Item>

          <Form.Item
            name="confirmPassword"
            dependencies={['password']}
            rules={[
              { required: true, message: '请确认密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                },
              }),
            ]}
          >
            <Input.Password prefix={<LockOutlined />} placeholder="确认密码" />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading} block>
              注册
            </Button>
          </Form.Item>

          <div className="login-link">
            已有账号？<Link to="/login">立即登录</Link>
          </div>
        </Form>
      </Card>
    </div>
  );
};

export default Register; 